package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.alibaba.android.arouter.facade.annotation.Route
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseRequestParams
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver
import com.kanshu.ksgb.fastread.doudou.common.urlrouter.UrlRouter
import com.kanshu.ksgb.fastread.doudou.common.util.*
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.module.personal.fragment.PersonCenterFragment
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.QuestionCategory
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import com.umeng.analytics.MobclickAgent
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_help_feedback.*
import kotlinx.android.synthetic.main.item_question_category.view.*

/**
 * 帮助与反馈
 */
@Route(path = ARouterConfig.PERSONAL_HELP_FEED_BACK)
class HelpFeedbackActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_help_feedback)
        title = "帮助与反馈"

        //标题栏右侧按钮 我的反馈
        val rightView = View.inflate(this, R.layout.right_feedback_layout, mTitle.getRightContainer())
        val feedback_red_point = rightView.findViewById<ImageView>(R.id.feedback_red_point)
        val isReadFeedback = StorageUtils.getPreference(activity, Constants.SP_NAME, "is_read_feedback_" + UserUtils.getUserId(), false)
        feedback_red_point.setVisibility(if (isReadFeedback) View.VISIBLE else View.GONE)
        rightView.setOnClickListener {
            ARouterUtils.toActivityForResult(this@HelpFeedbackActivity,ARouterConfig.PERSONAL_MY_FEED_BACK,1000)
//            startActivityForResult(Intent(this@HelpFeedbackActivity, MyFeedbackActivity::class.java), 1000)
        }

        submit.setOnClickListener {
            val editInfo = edit_info.text.toString()
            if (TextUtils.isEmpty(editInfo)) {
                ToastUtil.showMessage(this, "内容不能为空")
                return@setOnClickListener
            }
            if (!NetUtils.isNetworkAvailable(this)) {
                ToastUtil.showMessage(this, getString(R.string.standard_net_tip))
                return@setOnClickListener
            }
            //上传任务信息
            val dialog = LoadingDialog(this, "正在提交中")
            dialog.setCancelable(false)
            dialog.show()
            val params = BaseRequestParams()
            val helper = RetrofitHelper.getInstance()
            val map = mutableMapOf<String, String>()
            map["content"] = editInfo
            map["contact"] = edit_contact.text.toString().trim()
            map["phone_type"] = android.os.Build.MODEL
            map["app_version"] = Utils.getVersionCode(this).toString()
            helper.createService(PersonCenterService::class.java).submitFeedback(map)
                    .compose(asyncRequest())
                    .subscribe({
                        ToastUtil.showMessage(this@HelpFeedbackActivity, "反馈提交成功!")
                        dialog.dismiss()
                        finish()
                    }, {
                        dialog.dismiss()
                        ToastUtil.showMessage(this, "提交失败！")
                    })
        }


        help_feedback_hint.text = getString(R.string.help_feedback_hint, UserUtils.getUserId(), getString(R.string.app_name), Utils.getVersionName(this))

        question_category.layoutManager = GridLayoutManager(this, 4)
        val adapter = QuestionCategoryAdapter()
        question_category.adapter = adapter

        //获取常见问题分类
        RetrofitHelper.getInstance()
                .createService(PersonCenterService::class.java)
                .questionCategory
                .compose(asyncRequest())
                .subscribe(object : BaseObserver<List<QuestionCategory>>() {
                    override fun onResponse(tBaseResult: BaseResult<List<QuestionCategory>>?, t: List<QuestionCategory>?, disposable: Disposable?) {
                        adapter.data = t
                        adapter.notifyDataSetChanged()
                    }

                    override fun onError(code: Int, errDesc: String?) {
                        ToastUtil.showMessage(this@HelpFeedbackActivity, errDesc)
                    }
                })

        qq_service.text = getString(R.string.qq_service, MMKVDefaultManager.getInstance().getCustomerServiceQQ())
        online.setOnClickListener {
            PersonCenterFragment.showCustomServiceDialog(this)
        }

    }

    class QuestionCategoryAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        var data: List<QuestionCategory>? = null
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return object : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_question_category, parent, false)) {}
        }

        override fun getItemCount(): Int = data?.size ?: 0

        /**
         * 常见问题解答
         * @param context
         * @param category
         */
        fun startFrequentlyAskedQuestions(context: Context, category: QuestionCategory) {
            val str = JsonUtils.jsonStrToMap(JsonUtils.bean2Json(category))
            val url = Utils.linkUrl(context.getString(R.string.base_jump_url) + context.getString(R.string.frequently_asked_questions), str)
            UrlRouter.from(context).jump(url)
        }


        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val q = data?.get(position) ?: return
            holder.itemView.question_category_title.text = q.title
            holder.itemView.setOnClickListener {
                startFrequentlyAskedQuestions(holder.itemView.context, q)

            }
        }

    }



    override fun onDestroy() {
        super.onDestroy()
        Utils.hideSoftKeyboard(edit_info)
        Utils.hideSoftKeyboard(edit_contact)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        MobclickAgent.onPageStart(javaClass.simpleName)
    }

    override fun onPause() {
        super.onPause()
        Utils.hideSoftKeyboard(edit_info)
        Utils.hideSoftKeyboard(edit_contact)
        MobclickAgent.onPause(this)
        MobclickAgent.onPageEnd(javaClass.simpleName)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            finish()
        }
    }

}
